//
//  BBLoginSmsCodeView.m
//  BBLoginModule
//
//  Created by mac on 2023/3/9.
//

#import "MPLoginSmsCodeView.h"

@interface MPLoginCustomTextFiled : UITextField

@property (nonatomic, copy) void(^deleteCallBack)(void);

@end

@implementation MPLoginCustomTextFiled

- (void)deleteBackward {
    [super deleteBackward];
    if (self.deleteCallBack) {
        self.deleteCallBack();
    }
}

@end

@interface MPLoginSmsCodeView()<UITextFieldDelegate>

@property (nonatomic, strong) MPLoginCustomTextFiled *tf;
@property (nonatomic, strong) UIView *indicatorView;

@property (nonatomic, strong) NSMutableArray <UILabel *>*labels;

@property (nonatomic, assign) NSUInteger count;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat spaceWidth;

@end

@implementation MPLoginSmsCodeView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.labels = [NSMutableArray array];
    }
    return self;
}

+ (instancetype)codeViewWithCount:(NSUInteger)count itemWidth:(CGFloat)itemWidth spaceWidth:(CGFloat)spaceWidth {
    MPLoginSmsCodeView *codeView = [[MPLoginSmsCodeView alloc] initWithFrame:CGRectMake(0, 0, 228, 60)];
    codeView.count = count;
    codeView.itemWidth = itemWidth;
    codeView.spaceWidth = spaceWidth;
    [codeView refreshLayout];
    return codeView;
}

- (void)refreshLayout {
    for (UIView *subView in self.subviews) {
        [subView removeFromSuperview];
    }
    [self.labels removeAllObjects];
    
    CGFloat itemWidth = self.itemWidth;
    CGFloat itemHeight = self.itemWidth;
    CGFloat leftMargin = (CGRectGetWidth(self.frame)-itemHeight*self.count-self.spaceWidth*(self.count-1))*0.5;
    for (int i=0; i<self.count; i++) {
        CGRect frame = CGRectMake(leftMargin+(itemWidth+self.spaceWidth)*i, (CGRectGetHeight(self.frame)-itemWidth)*0.5, itemHeight, itemHeight);
        UILabel *label = [[UILabel alloc] initWithFrame:frame];
        label.font = [UIFont boldSystemFontOfSize:36];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor main_Text_color];
       
        CGRect lineFrame = CGRectMake((itemWidth-45)/2, CGRectGetMaxY(frame)-1, 45, 1);
        UIView *underLine = [[UIView alloc] initWithFrame:lineFrame];
        underLine.backgroundColor = [UIColor assist_GrayLine_color];
        [label addSubview:underLine];
        [self.labels addObject:label];
        [self addSubview:label];
    }
    
    UILabel *firstLabel = [self.labels firstObject];
    
    UIView *indicatorView = [[UIView alloc] initWithFrame:CGRectZero];
    self.indicatorView = indicatorView;
    indicatorView.backgroundColor = [UIColor main_Color];
    [self addSubview:indicatorView];
    [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(3, 30));
        make.centerY.equalTo(self);
        make.centerX.equalTo(firstLabel);
    }];
    
    MPLoginCustomTextFiled *tf = [[MPLoginCustomTextFiled alloc] initWithFrame:CGRectZero];
    tf.hidden = YES;
    tf.delegate = self;
    tf.keyboardType = UIKeyboardTypeNumberPad;
    [tf addTarget:self action:@selector(tfEditingChanged:) forControlEvents:(UIControlEventEditingChanged)];
    self.tf = tf;
    [self addSubview:tf];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.repeatCount = MAXFLOAT;
    animation.duration = 1.0;
    animation.fromValue = @1.0;
    animation.toValue = @0;
    [indicatorView.layer addAnimation:animation forKey:@"indicator"];
}

- (void)tfEditingChanged:(UITextField *)textField {
    if (textField.text.length > self.count) {
        textField.text = [textField.text substringWithRange:NSMakeRange(0, self.count)];
    }
    for (int i = 0; i < self.count; i++) {
        UILabel *label = [self.labels objectAtIndex:i];
        if (i < textField.text.length) {
            label.text = [textField.text substringWithRange:NSMakeRange(i, 1)];
        } else {
            label.text = nil;
        }
    }
    
    NSInteger currentIndex = textField.text.length;
    if (currentIndex < self.labels.count) {
        self.indicatorView.hidden = NO;
        UILabel *nextLabel = self.labels[currentIndex];
        [self.indicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(3, 30));
            make.centerY.equalTo(self);
            make.centerX.equalTo(nextLabel);
        }];
    }
    
    if (textField.text.length >= self.count) {
        self.indicatorView.hidden = YES;
    }
    
    if (textField.text.length == self.count && self.inputCompleteCallBack) {
        self.inputCompleteCallBack(textField.text);
        [self.tf resignFirstResponder];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length > 0 && textField.text.length >= self.count) {
        [self.tf resignFirstResponder];
    }
    NSString *match = [NSString stringWithFormat:@"^[0-9]{0,%@}$", @(self.count)];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", match];
    if (![predicate evaluateWithObject:string]) {
        return NO;
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (!self.tf.isFirstResponder) {
        [self.tf becomeFirstResponder];
    }
}

- (void)codeViewBecomeFirstResponser {
    [self.tf becomeFirstResponder];
}

- (NSString *)code {
    return self.tf.text;
}

@end
